import { Button, Form, Input } from "antd";
import React, { useEffect, useState } from "react";
import { resetPasswordHandle } from "../../service/account";
import style from "./style.less"
import { ResetPasswordInfo } from "../../interface/account";
import { useNavigate } from "react-router-dom";
import { checkCode, senCode } from "../../service/code";
import { myTip } from "../../tools/publicFun";

export default function RetrievePassword() {
  const navigate = useNavigate()
  const [password, setPassword] = useState<string>('')
  const [confirm, setConfirm] = useState<string>('')
  const [samePassword, setSamePassword] = useState<boolean>(true)
  const [safePassword, setSafePassword] = useState<boolean>(true)
  const [account, setAccount] = useState<string>('')
  const [code, setCode] = useState<string>('')
  const [sentCode, setSentCode] = useState<boolean>(false)
  const [time, setTime] = useState<string>('179')


  useEffect(() => {
    let timer = 59
    const countTime = setInterval(() => {
      setTime((timer--).toString())
      return () => {
        setTime("179")
      }
    }, 1000)
    if (sentCode) {
      setTimeout(() => {
        clearInterval(countTime)
        setSentCode(false)
      }, 180000)
      myTip("验证码发送成功，三分钟内有效", "success")
    } else {
      clearInterval(countTime)
    }
    return () => {

      clearInterval(countTime)
    }
  }, [sentCode])
  // 发送验证码
  async function handlesendCode() {
    // 电话号码正则验证
    if (/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(account)) {
      const data = await senCode({ account: account })
      if (data.stat === 'ok') {
        setSentCode(true)
      } else {
        myTip(data.msg, "fail")
      }
    } else {
      myTip("请填入正确的电话号码", "warning")
    }

  }
  // 前端验证两次输入密码是否相同
  function checkSamePassword(confirmPassword: string) {
    if (confirmPassword !== password) {
      setSamePassword(false)
    } else {
      setSamePassword(true)
    }
  }
  // 前端验证密码是否满足密码的复杂度
  function checkSafePassword(password: string) {
    if (password === '' || !!password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/)) {
      setSafePassword(true)
    } else {
      setSafePassword(false)
    }
  }
  // 验证验证码
  async function handleCheckCode(params: ResetPasswordInfo) {
    const data = await checkCode({ account: account!, code: params.confirmCode })
    if (data.stat === 'ok') {
      resetPassword(params)
    } else {
      myTip(data.msg, "fail")
    }
  }

  async function resetPassword(params: ResetPasswordInfo) {
    const data = await resetPasswordHandle(params)
    if (data.stat === 'ok') {
      alert("修改成功，点击确认跳转登陆页面")
      navigate("/login")
    } else {
      myTip("修改失败，" + data.msg, "fail")
    }
  }

  return (
    <React.Fragment>
      <div className={style.content}>
        <div className={style.accountInput}>
          <div className={style.inputPart}>
            <div>账 号：</div>
            <Input
              className={style.inputBox}
              type="tel"
              onChange={(value) => {
                setAccount(value.target.value)
              }}
            />
          </div>
          <div>
            <Button
              type={"primary"}
              className={style.submitButton}
              disabled={(account.length !== 11) || sentCode}
              onClick={() => {
                handlesendCode()
              }}
            >
              {sentCode ? `${time}s之后可重新发送` : "发送验证码"}
            </Button>
          </div>
        </div>
        <div className={style.inputPart}>
          <div>验证码：</div>
          <Input onChange={(value) => { setCode(value.target.value) }} className={style.inputBox} />
        </div>
        <div className={style.resetPassword} >
          <Form
            className={style.inputList}
            onFinish={(value) => {
              handleCheckCode({
                ...value,
                account: account,
                confirmCode: code
              })
            }}>
            <Form.Item className={style.inputPart} label="请输入您的新密码" name="newPassword">
              <Input
                value={password}
                onBlur={(value) => {
                  setPassword(value.target.value);
                  checkSafePassword(value.target.value)
                }}
                type={"password"}
                className={style.inputBox}
              />
            </Form.Item>
            <Form.Item className={style.inputPart} label="请验证您的新密码" name="newConfirmPassword">
              <Input
                value={confirm}
                onBlur={(value) => {
                  setConfirm(value.target.value);
                  checkSamePassword(value.target.value)
                }}
                type={"password"}
                className={style.inputBox}
              />
            </Form.Item>
            {safePassword ?
              <></> :
              <div className={style.passwordTip}>
                密码必须大于8位，小于十六位，包含大写字母，小写字母和数字
              </div>
            }
            {samePassword ?
              <></> :
              <div className={style.passwordTip} >
                两次输入的密码不同，请重新输入
              </div>
            }
            <Form.Item>
              <Button
                className={style.submitButton}
                disabled={(!(safePassword && samePassword)) || password === ''}
                type={"primary"}
                htmlType="submit"
              >
                提交修改
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </React.Fragment>
  )
}